// 压缩器 - 处理问卷结果的压缩和解压缩
import { getAssessResult, getQuestionnaire } from './schema-loader.js'

export const assessKeys = ["a1", "a2", "a3", "a4", "a5", "a6"];

/**
 * 问卷结果压缩解压缩管理器
 */
export class ResultCompressor {
    constructor() {
        // 直接使用 schema-loader 的接口，不需要成员变量
    }

    /**
     * 压缩 Screening 结果
     * @param {Array} results - 原始结果数组
     * @returns {Object} 压缩后的结果对象
     */
    compressScreeningResult(results) {
        // results: array of { id, threshold, score, risk, ... }
        // compress to object keyed by id with essential fields
        const obj = {};
        if (!Array.isArray(results)) return obj;
        for (const item of results) {
            if (!item || !item.id) continue;
            obj[item.id] = {
                score: item.score,
                risk: item.risk,
                // threshold 可以从前端配置还原，不需要存储
            };
        }
        return obj;
    }

    /**
     * 解压缩 Screening 结果
     * @param {Object} compressed - 压缩的结果对象（result: {details: {...}, result: {...}}中的result.result）
     * @returns {Array} 完整的结果数组
     */
    decompressScreeningResult(compressed) {
        // 处理新的后端存储格式：result.result 是需要解压的数据
        if (!compressed) return [];

        // 直接从 schema-loader 获取 screening 配置
        const screeningConfig = getQuestionnaire('screening');
        if (!screeningConfig || !screeningConfig.score_judge) return [];

        const results = [];
        for (const judge of screeningConfig.score_judge) {
            const compressedItem = compressed[judge.id];
            if (!compressedItem) continue;

            results.push({
                id: judge.id,
                name: judge.name,
                iconUrl: judge.iconUrl,
                score: compressedItem.score,
                risk: compressedItem.risk,
                threshold: judge.threshold, // 从原始配置还原
                assessment: judge.assessment,
                results: judge.results, // 从原始配置还原
            });
        }
        return results;
    }

    /**
     * 压缩 Assessment 结果
     * @param {Object} result - 原始结果对象
     * @returns {Object} 压缩后的结果对象
     */
    compressAssessResult(result) {
        const compressed = {};
        // 只保留每个submodule的result和score
        for (const key of assessKeys) {
            console.log("key", key);
            const item = result[key];
            if (item == null) {  // 未做评估做填充
                compressed[key] = null;
                continue;
            }
            const compressedItem = {};
            for (const [name, index] of Object.entries(item)) {
                if (name == "total") {
                    compressedItem["total"] = item[name];
                    continue;
                }
                const subitem = item[name];
                // 保留cid, value, score
                const cid = subitem.result.cid;
                compressedItem[cid] = {
                    value: subitem.result.value,
                    score: subitem.score,
                };
            }
            compressed[key] = compressedItem;
        }
        return compressed;
    }

    /**
     * 解压缩 Assessment 结果
     * @param {Object} compressed - 压缩的结果对象
     * @returns {Object} 完整的结果对象
     */
    decompressAssessResult(compressed) {
        if (!compressed) return {};

        const assessResultConfig = getAssessResult();
        const decompressed = {};
        for (const key of assessKeys) {
            const basicResult = assessResultConfig[key];

            const item = {};
            // init module basic info
            item.title = basicResult.title;
            item.iconUrl = basicResult.iconUrl;
            
            item.total = compressed[key]?.total ?? {
                max: basicResult.score.max,
                score: basicResult.score.default,
                reverse: basicResult.score.reverse ?? false,
            };
            
            item.submodules = {};
            // init submodule results & advices
            let aids = [];
            for (const subKey of basicResult.submodule_keys) {
                const submodule = {};
                const subBasicResult = basicResult.submodules[subKey];
                const value = compressed[key] == null || compressed[key][subKey] == null || compressed[key][subKey].value == null ? subBasicResult.default : compressed[key][subKey].value;
                submodule.title = subBasicResult.title;
                submodule.value = value;
                const basicValueItem = subBasicResult.values.find((v) => v.value == value);
                if (basicValueItem) {
                    submodule.content = basicValueItem.content;
                    aids.push(...basicValueItem.aid);
                }
                item.submodules[subKey] = submodule;
            }
            item.advices = aids;
            decompressed[key] = item;
        }
        return decompressed;
    }

    /**
     * 压缩 Healthtest 结果
     * @param {Object} result - 原始结果对象
     * @returns {Object} 压缩后的结果对象
     */
    compressHealthtestResult(result) {
        const compressed = {};
        
        // h1_important_effect: 压缩评分结果
        if (result.h1) {
            const h1Result = {};
            for (const [key, item] of Object.entries(result.h1)) {
                if (item.result) {
                    // 使用cid作为key而不是dimension id
                    const cid = item.result.cid;
                    h1Result[cid] = {
                        value: item.result.value
                    };
                }
            }
            compressed.h1 = h1Result;
        }
        
        // h2_dangerous_effect: 不产生评分结果，保持空对象
        compressed.h2 = result.h2 || {};
        
        return compressed;
    }

    /**
     * 解压缩 Healthtest 结果
     * @param {Object} compressed - 压缩的结果对象
     * @returns {Object} 完整的结果对象
     */
    decompressHealthtestResult(compressed) {
        if (!compressed) return {};

        const h1Config = getQuestionnaire('h1_important_effect');
        const decompressed = {};

        // 解压h1结果
        if (compressed.h1 && h1Config) {
            const h1Result = {};
            for (const judge of h1Config.score_judge) {
                // 遍历所有intervals找到匹配的cid
                for (const interval of judge.intervals) {
                    const cid = interval.result.cid;
                    const compressedItem = compressed.h1[cid];
                    if (!compressedItem) continue;

                    // 检查value是否匹配
                    if (interval.result.value === compressedItem.value) {
                        h1Result[judge.id] = {
                            name: judge.name,
                            result: interval.result
                        };
                        break;
                    }
                }
            }
            decompressed.h1 = h1Result;
        }

        // h2不需要解压
        decompressed.h2 = null;

        return decompressed;
    }

    /**
     * 获取指定问卷的压缩器
     * @param {string} type - 问卷类型
     * @returns {Object} 包含compress和decompress方法的压缩器对象
     */
    getCompressor(type) {
        switch (type) {
            case 'screening':
                return {
                    compress: (results) => this.compressScreeningResult(results),
                    decompress: (compressed) => this.decompressScreeningResult(compressed)
                };
            case 'assessment':
                return {
                    compress: (result) => this.compressAssessResult(result),
                    decompress: (result) => this.decompressAssessResult(result)
                };
            case 'healthtest':
                return {
                    compress: (result) => this.compressHealthtestResult(result),
                    decompress: (result) => this.decompressHealthtestResult(result)
                };
            default:
                throw new Error(`Unsupported questionnaire type: ${type}`);
        }
    }
}

// 创建全局实例
const resultCompressor = new ResultCompressor();

/**
 * 获取问卷结果压缩器
 * @param {string} type - 问卷类型 (screening, assessment, healthtest)
 * @returns {Object} 包含compress和decompress方法的压缩器对象
 */
export const getCompressor = (type) => resultCompressor.getCompressor(type);

export { resultCompressor };